import os
import re
import threading
from collections import defaultdict
from time import sleep

import pandas as pd
import numpy as np
import time
from commen.log import Logger
import openpyxl
import datetime
import commen.config


def output_result(result_data, interval=200):
    total = 0
    total_number = 0
    for t, num in sorted(result_data.items()):
        if int(t) > 100000:
            continue
        print(f"{t}ms:{num}个")
        total += int(t) * num
        total_number += num
    standard = total_number * interval
    print(f"总数：{total_number}")
    if total / standard < 1:
        print(f"{interval}ms连续率：{total / standard}")
    else:
        print(f"{interval}ms连续率：{standard / total}")


def ImuDatacontinuity():
    # ---------读取config文件获取筛选字段内容--------------------------
    # caninskey = commen.config.global_config.getRaw('keywords', 'cankeyins')
    caninskey = 'Rx 2 0x131'

    # ---------读取config文件获取筛选字段内容--------------------------
    logger = Logger(logger='TestMylog').getlog()
    # -----------------------创建excel--------------------------------------------
    # 获取当前时间
    time_now = time.strftime("%Y%m%d-%H%M", time.localtime())
    # 获取当前路径
    result_root = os.getcwd()
    root = os.getcwd()
    result_path = result_root + r'\result' + "\\" + time_now
    log_path = root + r'\original-logfile' + '\\'
    # -----遍历对比log路径获取要对比的文件名路径信息----------------------
    for root, dirs, files in os.walk(log_path):
        for file in files:
            # if "Data" in file:
            #     aa = os.path.join(root, file)
            # if "can" in file:
            #     bb = os.path.join(root, file)
            if "can" in file:
                bb = os.path.join(root, file)

    # -----遍历对比log路径获取要对比的文件名路径信息----------------------
    book = openpyxl.Workbook()  # 打开一个将写的文件
    sheet = book.create_sheet(index=0)  # 在将写的文件创建sheet
    saveExcel = result_path + "INS连续性验证结果.xlsx"
    sheet.cell(1, 2).value = "canlog中接收该条数据系统时间原值"
    sheet.cell(1, 3).value = "ins数据utc时间16进制原值"
    sheet.cell(1, 4).value = "ins数据发出的UTC时间T1（时区+8）"
    sheet.cell(1, 5).value = "can追加年月日系统时间T2"
    sheet.cell(1, 6).value = "T2减T1差值"

    row = 1
    # -----------------------创建excel--------------------------------------------

    canfile = open(bb, 'r', encoding='gbk')  # 打开can.log目标文件
    # dataprocfile = open(aa, 'r', encoding='UTF-8')  # 打开dataproc.log文件
    logger.info("打开目标文件")
    canlines = canfile.readlines()
    # inslines = dataprocfile.readlines()
    logger.info("获取内容")
    num = 0
    cansystemlist = []  # canlog中系统时间
    canmessage_UTCtimelist = []  # 输出到can数中的utc时间列表，转换成时间后
    canmessage_16timelist = []  # 输出到can数中的utc时间，16进制原值转换前
    logger.info("开始逐行读取")
    number = 0
    for canline in canlines:  # 对canlog内容 进行逐行读取
        if caninskey in canline:

            aftertime = canline[:canline.index("Rx")]

            caninsdatamessage = canline.split("s-fd-brs 64")
            caninsdatamessage = caninsdatamessage[1].rstrip()
            caninsdatamessage = caninsdatamessage.lstrip()
            caninsdatamessage = caninsdatamessage.replace(" ", "")
            caninsdatamessage = caninsdatamessage[100:111]
            # utctime = "0x" + caninsdatamessage  # 拼接成代表时间的16进制
            utctime = int(caninsdatamessage, 16)  # 把16进制时间字符串转换成十进制
            if utctime == 0:
                continue

            receivetime_old = bin(int(utctime))  # 十进制字符串转换成二进制
            # -------------------------二进制字符串转换成整数并拼接成时间------------------------------------

            year = pd.to_datetime("1980-01-06") + pd.DateOffset(days=int(receivetime_old[0:16], 2))
            year = year.strftime('%Y-%m-%d')
            hour = str(int(receivetime_old[16:22], 2))
            minute = str(int(receivetime_old[22:28], 2))
            seconds = str(int(receivetime_old[28:34], 2))
            milliseconds = str(int(receivetime_old[34:], 2))
            if int(hour) < 10:
                hour = "0" + str(hour)
            if int(minute) < 10:
                minute = "0" + str(minute)
            if int(seconds) < 10:
                seconds = "0" + str(seconds)
            if int(milliseconds) < 10:
                milliseconds = "00" + str(milliseconds)
            if 10 <= int(milliseconds) < 100:
                milliseconds = "0" + str(milliseconds)
            sf_receivetime = year + " " + hour + ":" + minute + ":" + seconds + "." + milliseconds
            canmessage_UTCtimelist.append(sf_receivetime)
            cansystemlist.append(aftertime.rstrip())
            canmessage_16timelist.append(caninsdatamessage)
    logger.info("开始判断差值")
    disc = defaultdict(int)
    for i in range(len(canmessage_UTCtimelist)):
        row = row + 1
        if int(i) + 2 > len(canmessage_UTCtimelist):  # 执行到最后一个之后跳出循环
            break

        else:
            logger.info("开始计算差值")
            mcucomm_time1 = canmessage_UTCtimelist[i].rstrip()
            mcucomm_time2 = mcucomm_time1.lstrip()
            DataProc_time1 = cansystemlist[i].lstrip()
            DataProc_time2 = list(DataProc_time1)
            DataProc_time2[8] = "."
            DataProc_time3 = "".join(DataProc_time2)
            DataProc_time = mcucomm_time2[:mcucomm_time2.index(" ")] + " " + DataProc_time3
            cantime1 = cansystemlist[i]
            cantime1 = list(cantime1)
            cantime1[8] = "."
            cantime1 = "".join(cantime1)
            cantime2 = cansystemlist[int(i) + 1]
            cantime2 = list(cantime2)
            cantime2[8] = "."
            cantime2 = "".join(cantime2)
            try:
                mcucomm_time = (datetime.datetime.strptime(mcucomm_time2, '%Y-%m-%d %H:%M:%S.%f') + datetime.timedelta(
                    hours=8)).strftime("%Y-%m-%d %H:%M:%S.%f")
                t1 = datetime.datetime.strptime(mcucomm_time, '%Y-%m-%d %H:%M:%S.%f')
                t2 = datetime.datetime.strptime(mcucomm_time2[:mcucomm_time2.index(" ")] + " " + DataProc_time3,
                                                '%Y-%m-%d %H:%M:%S.%f')
                sheet.cell(row, 2).value = str(cansystemlist[i])
                sheet.cell(row, 3).value = str(canmessage_16timelist[i])
                sheet.cell(row, 4).value = str(mcucomm_time)
                sheet.cell(row, 5).value = str(
                    datetime.datetime.strptime(mcucomm_time2[:mcucomm_time2.index(" ")] + " " + DataProc_time3,
                                               '%Y-%m-%d %H:%M:%S.%f'))

            except:
                print(cansystemlist[i])
                sheet.cell(row, 2).value = str(cansystemlist[i])
                sheet.cell(row, 3).value = str(canmessage_16timelist[i])
                sheet.cell(row, 4).value = str(canmessage_UTCtimelist[i])
                sheet.cell(row, 5).value = str(DataProc_time)

            try:

                t1 = int(time.mktime(t1.timetuple()) * 1000.0 + t1.microsecond / 1000.0)
                t2 = int(time.mktime(t2.timetuple()) * 1000.0 + t2.microsecond / 1000.0)
                deltat = int(t2) - int(t1)
                sheet.cell(row, 6).value = str(deltat)
                disc[deltat] += 1

            except:
                # sheet.cell(row, 7).value = str(int((t2 - t1).microseconds / 1000))
                sheet.cell(row, 6).value = "异常"
                disc["异常"] += 1

            # try:
            #     can1 = datetime.datetime.strptime(cantime1, '%H:%M:%S.%f')
            #     can2 = datetime.datetime.strptime(cantime2, '%H:%M:%S.%f')
            #     candetat = (can2 - can1).microseconds / 1000
            #     sheet.cell(row, 9).value = str(int(candetat))
            # except:
            #     sheet.cell(row, 9).value ="异常"

    # --------------------------二进制字符串转换成整数并拼接成时间------------------------------------
    sleep(2)
    print(disc)
    output_result(disc, 200)
    # ----------------------将对比的数据写入excel---------------------------------
    book.save(saveExcel)
    # ----------------------将对比的数据写入excel---------------------------------


ImuDatacontinuity()
